import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker_plus/picker.dart';
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/user.dart';

import '../common/constants.dart';

class SettingScreen extends StatefulWidget {
  @override
  _SettingScreenState createState() => _SettingScreenState();
}

class _SettingScreenState extends State<SettingScreen> {
  final LocalAuthentication _localAuthentication = LocalAuthentication();
  bool _canCheckBiometrics = false;

  @override
  void initState() {
    _checkBiometrics();
    super.initState();
  }

  Future<void> _checkBiometrics() async {
    bool canCheckBiometrics = false;
    bool isSupported = false;
    try {
      canCheckBiometrics = await _localAuthentication.canCheckBiometrics;
      isSupported = await _localAuthentication.isDeviceSupported();
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;

    setState(() {
      _canCheckBiometrics = canCheckBiometrics && isSupported;
    });
  }

  @override
  Widget build(BuildContext context) {
    final _user = context.read<User>();

    List<PickerItem> _items = [];
    themeList.forEach((_k, _v) => _items.add(PickerItem(text: _v['text'], value: _k)));

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('设置'),
      ),
      body: PublicList(
        children: <Widget>[
          _canCheckBiometrics
              ? ListTile(
                  title: Text(
                    '指纹解锁',
                  ),
                  trailing: Switch(
                      value: _user.needBiometrics,
                      onChanged: (bool value) async {
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        prefs.setBool('needBiometrics', value);
                        setState(() {
                          _user.needBiometrics = value;
                        });
                      }),
                )
              : SizedBox(),
          ListTile(
            title: Text('主题颜色'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [_items.firstWhere((item) => item.value == _user.themeMode).text ?? SizedBox(), Icon(Icons.chevron_right)],
            ),
            onTap: () async {
              await Picker(
                adapter: PickerDataAdapter(
                  data: _items,
                ),
                confirmText: '确定',
                cancelText: '取消',
                onConfirm: (Picker picker, List value) async {
                  final _themeMode = picker.getSelectedValues()[0];
                  SharedPreferences prefs = await SharedPreferences.getInstance();
                  prefs.setString('themeMode', _themeMode);
                  setState(() {
                    _user.themeMode = _themeMode;
                  });
                },
              ).showModal(context);
            },
          ),
          ListTile(
            title: Text('关于'),
            trailing: Icon(Icons.chevron_right),
            onTap: () {
              Navigator.pushNamed(context, '/about');
            },
          ),
        ],
      ),
    );
  }
}
